package com.ksj.util;

import com.aliyun.ocr_api20210707.*;
import com.aliyun.ocr_api20210707.models.*;
import com.alibaba.fastjson.*;
import com.aliyun.teautil.models.RuntimeOptions;

import java.io.*;
import java.util.*;

import static com.ksj.util.Sample.createClient;

public class IdCardRecognition {

    public static HashMap<String, String> recognizeIdCard(InputStream imageStream) {
        HashMap<String, String> result = new HashMap<>();

        try {
            // 1. 创建客户端
            Client client = createClient();

            // 2. 创建请求对象
            RecognizeIdcardRequest request = new RecognizeIdcardRequest();

            // 3. 正确设置请求体（关键修改）
            request.body = imageStream;  // 直接赋值InputStream

            // 4. 调用OCR接口
            RuntimeOptions runtime = new RuntimeOptions();
            RecognizeIdcardResponse response = client.recognizeIdcardWithOptions(request, runtime);

            // 5. 解析响应
            JSONObject data = JSONObject.parseObject(response.body.data)
                    .getJSONObject("data")
                    .getJSONObject("face")
                    .getJSONObject("data");

            result.put("name", data.getString("name"));
            result.put("idNumber", data.getString("idNumber"));

        } catch (Exception e) {
            result.put("error", "识别失败: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

}